#! /usr/bin/env python
#coding=utf-8

import user
import Log
import Getconfig
import udict
import sys
import os
import factory

if __name__ == '__main__':
    # 把程序目录加到sys.path里去
    apppath = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.split(apppath)[0])
    
    # 初始化User
    appuser = user.User(name='anewrer')
    appuser.config = Getconfig.Getconfig()
    appuser.log = Log.Log(appuser.config)
    appuser.level = 'normal'
    
    # 初始化Doc，Doc是由配置文件确定的，全局只需要一个
    appdoc = factory.DocFactory(appuser).Doc(appuser)
    appdoc.open_conn()

    st = True
    try:
        while st:
            st = sys.stdin.readline()
            uocop = st.rstrip().split(' ')

            uocname = uocop[0]
            uocparams = None
            if not uocname or len(uocname) < 1:
                continue
            if not udict.uocdict.get(uocname):
                appuser.log.writeLog('undefined uoc.', 'info')
                continue
            if len(uocop) > 1:
                uocparams = uocop[1:]
            pmod = factory.UocFactory(uocname)
            if not pmod:
                appuser.log.writeLog('import uoc module fail.', 'fatal')

            myuoc = pmod.Uoc(uocname, uocparams=uocparams, user=appuser, doc=appdoc)
            myuoc.excute()
    except Exception, e:
        # 关闭Doc
        appdoc.close_conn()
        appuser.log.writeLog('melobook must exit', 'error')
        sys.exit()
    
    appdoc.close_conn()
    appuser.log.writeLog('melobook exit', 'info')
